﻿'use strict';

var context = SP.ClientContext.get_current();
var user = context.get_web().get_currentUser();

// This code runs when the DOM is ready and creates a context object which is needed to use the SharePoint object model
$(document).ready(function () {
    getUserName();
    processRequestedFact();
});

// This function prepares, loads, and then executes a SharePoint query to get the current users information
function getUserName() {
    context.load(user);
    context.executeQueryAsync(onGetUserNameSuccess, onGetUserNameFail);
}

// This function is executed if the above call is successful
// It replaces the contents of the 'message' element with the user name
function onGetUserNameSuccess() {
    $('#message').text('Hello ' + user.get_title());
}

// This function is executed if the above call fails
function onGetUserNameFail(sender, args) {
    alert('Failed to get user name. Error:' + args.get_message());
}

var list;
var listName = "Facts";

function insertFacts() {
    this.createFact('Rubber bands last longer when refrigerated.');
    this.createFact('Peanuts are one of the ingredients of dynamite.');
    this.createFact('The national anthem of Greece has 158 verses. No one in Greece has memorized all 158 verses.');
    this.createFact('There are 293 ways to make change for a dollar.');
    this.createFact("The average person's left hand does 56% of the typing.");
    this.createFact('A shark is the only fish that can blink with both eyes.');
    this.createFact('There are more chickens than people in the world.');
}

var web = context.get_web();

function createFact(factText) {
    list = web.get_lists().getByTitle(listName);

    var itemCreateInfo = new SP.ListItemCreationInformation();

    var listItem = list.addItem(itemCreateInfo);
    listItem.set_item('Title', factText);
    listItem.set_item('_Category', 'Useless');
    listItem.update();

    context.load(listItem);
    context.executeQueryAsync(onCreateFactSucceeded, onFailedAction);
}

function onCreateFactSucceeded(sender, args) {
    SP.UI.Notify.addNotification("Added fact to Facts list... (please reload page)", false);
}

function onFailedAction(sender, args) {
    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

var hostUrl;
var appWebUrl;
var source;
var listId;
var itemId;

var hostWeb;
var hostList;
var requestFact;

function processRequestedFact() {
    // Extract querystring parameters
    var params = document.URL.split("?")[1].split("&");
    for (var i = 0; i < params.length; i = i + 1) {
        params[i] = decodeURIComponent(params[i]);
        setQueryParam(params[i].split("=")[0], params[i].split("=")[1]);
    }

    // Add fact via CustomAction
    if (source) {
        var factory = new SP.ProxyWebRequestExecutorFactory(appWebUrl);
        context.set_webRequestExecutorFactory(factory);
        var appContextSite = new SP.AppContextSite(context, hostUrl);

        hostWeb = appContextSite.get_web();
        hostList = hostWeb.get_lists().getById(listId);
        requestFact = hostList.getItemById(itemId);

        context.load(hostWeb);
        context.load(hostList);
        context.load(requestFact, 'Title');

        context.executeQueryAsync(addRequestedFact, onFailedAction);
    }
}

function addRequestedFact(sender, args) {
    var title = requestFact.get_item("Title");
    createFact(title);
}

function setQueryParam(key, val) {
    switch (key) {
        case "SPAppWebUrl": appWebUrl = val; break;
        case "SPListId": listId = val; break;
        case "SPListItemId": itemId = val; break;
        case "SPHostUrl": hostUrl = val; break;
        case "Source": source = val; break;
        case "SPLanguage": break;
        case "SPClientTag": break;
        case "SPProductNumber": break;
    }
}